package com.leetcode.sort;

import java.util.Arrays;

public class MinorSum {

    public int mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left >= right) {
            return 0;
        }
        int mid = (left + right) >>> 1;
        int L = mergeSort(arr, left, mid, temp);
        int R = mergeSort(arr, mid + 1, right, temp);
        int C = merge(arr, left, mid, right, temp);
        return L + R + C;
    }

    private int merge(int[] nums, int left, int mid, int right, int[] temp) {
        System.arraycopy(nums, left, temp, left, right + 1 - left);
        int i = left;
        int j = mid + 1;
        int res = 0;
        for (int k = left; k <= right; k++) {
            if (i == mid + 1) {
                nums[k] = temp[j];
                j++;
            } else if (j == right + 1) {
                nums[k] = temp[i];
                i++;
            } else if (temp[i] <= temp[j]) {
//                找正序对，累加值
                res += temp[i] * (right - j + 1);
                nums[k] = temp[i];
                i++;
            } else {
                // temp[i] > temp[j]
                nums[k] = temp[j];
                j++;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int arr[] = {1, 3, 4, 2, 5};
        int temp[] = new int[arr.length];
        int res = new MinorSum().mergeSort(arr, 0, arr.length - 1, temp);
        System.out.println("归并排序后=" + Arrays.toString(arr));
        System.out.println("小和=" + res);
    }
    
}
